<template>
  <div class="container-box">
    <div class="table-wrap">
      <div class="filter-box">
        <el-form class="demo-form-inline" :inline="true" :model="query">
          <template v-for="(colmun, index) in columns.filter(d => d.isFilter)">
            <el-form-item v-if="colmun.key === 'cat_id'" :key="colmun.key" :label="colmun.title" :prop="colmun.key">
              <el-select v-model="query[colmun.key]" :placeholder="`请选择${colmun.title}`" filterable :clearable="colmun.clearable" @change="handleList(colmun.key, $event)">
                <el-option v-for="item in goodsCategory" :key="item.cat_id" :label="item.cat_name" :value="item.cat_id" />
              </el-select>
            </el-form-item>
            <el-form-item v-else-if="colmun.key === 'goods_name'" :key="colmun.key" :label="colmun.title" :prop="colmun.key">
              <el-select v-model="query[colmun.key]" :placeholder="`请选择${colmun.title}`" filterable :clearable="colmun.clearable" @change="handleList(colmun.key, $event)">
                <el-option v-for="item in goodsSelects" :key="item.value" :label="item.label" :value="item.label" />
              </el-select>
            </el-form-item>
            <el-form-item v-else-if="colmun.key === 'store_house_id'" :key="index" :label="colmun.title" :prop="colmun.key">
              <el-select v-model="query[colmun.key]" :placeholder="`请选择${colmun.title}`" :clearable="colmun.clearable" @change="handleList(colmun.key, $event)">
                <el-option v-for="item in storeHouseList" :key="item.id" :label="item.store_house_name" :value="item.id" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item :label="colmun.title" :prop="colmun.key" :key="index" v-if="colmun.key === 'stock'">
              <el-select v-model="query[colmun.key]" :placeholder="`请选择${colmun.title}`" :clearable="colmun.clearable" @change="handleList(item.key, $event)">
                <el-option
                  v-for="item in ['有', '无']"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item v-else :key="index" :label="colmun.title">
              <el-input v-model="query[colmun.key]" :placeholder="`请输入${colmun.title}`" :clearable="colmun.clearable" @change="handleList(colmun.key, $event)" />
            </el-form-item>
          </template>
        </el-form>
        <el-button-group>
          <el-button type="primary" icon="el-icon-plus" @click="handleTableOp('add')">新增商品</el-button>
          <el-button type="primary" icon="search" @click="getData">查询</el-button>
        </el-button-group>
        <!-- <el-button type="primary" icon="el-icon-plus" @click="handleTableOp('', 'addGoods')">新增商品</el-button> -->
      </div>
      <div class="table-box">
        <el-table :data="list" :border="true" :row-class-name="handleRowClass">
          <el-table-column type="expand">
            <template slot-scope="scope">
              <div v-if="scope.row.attrValue && scope.row.attrValue.length" class="" style="marginLeft: 20px">
                <!-- <el-form label-position="left">
                  <div>商品规格</div>
                  <el-form-item :label="item.attr_name" v-for="(item, index) in scope.row.attrData" :key="index">{{item.attr_values}}</el-form-item>
                </el-form> -->
                <el-descriptions title="商品规格">
                  <el-descriptions-item v-for="(item, index) in scope.row.attrData" :key="index" :label="item.attr_name">{{ item.attr_values }}</el-descriptions-item>
                </el-descriptions>
              </div>
              <div v-else class="">暂无数据</div>
            </template>
          </el-table-column>
          <template v-for="(item, index) in columns.filter(d => d.isTable)">
            <el-table-column :key="index" :prop="item.key" :label="item.title" :sortable="item.sortable" :width="item.width">
              <template slot-scope="scope">
                <div v-if="item.key === ''" class="">{{ scope.row[item.key] }}</div>
                <div v-else v-html="handleRowResult(item, scope.row)"></div>
              </template>
            </el-table-column>
            <!-- <el-table-column :key="index" :prop="item.key" :label="item.title" :sortable="item.sortable" :formatter="formatterColumn"> -->
              <!-- <template slot-scope="scope">
                <div v-if="item.key === ''" class="">{{ scope.row[item.key] }}</div>
                <div v-else class="">{{ handleRowResult(item, scope.row) }}</div>
              </template> -->
            <!-- </el-table-column> -->
          </template>
          <el-table-column label="操作" width="200px">
            <template slot-scope="scope">
              <div class="but-box">
                <el-button type="primary" icon="el-icon-edit" circle @click="handleTableOp('edit', scope.row)" />
                <el-button type="primary" icon="el-icon-edit" @click="handleTableOp('editAttr', scope.row)">规格</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination :current-page="paging.page" :page-sizes="pageSizes" :page-size="paging.limit" layout="total, sizes, prev, pager, next, jumper" :total="paging.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <el-dialog :title="(dialogForm.id ? '编辑' : '新增') + '商品'" :visible.sync="dialogVisible" :show-close="false" :close-on-click-modal="false">
      <el-form ref="dialogForm" :model="dialogForm" :rules="rules" label-width="120px">
        <template v-for="(column, index) in dialogColums.filter(d => d.isForm)">
          <el-form-item v-if="column.key === 'cat_id'" :key="index" :label="column.title" :prop="column.key">
            <el-select v-model="dialogForm[column.key]" :placeholder="`请选择${column.title}`" style="width: 100%;">
              <el-option v-for="item in goodsCategory" :key="item.cat_id" :label="item.cat_name" :value="item.cat_id" />
            </el-select>
          </el-form-item>
          <el-form-item v-else :key="index" :label="column.title" :prop="column.key">
            <el-input v-if="column.type === 'number'" v-model.number="dialogForm[column.key]" :type="column.type" :placeholder="`请输入${column.title}`" />
            <el-input v-else v-model="dialogForm[column.key]" :type="column.type" :placeholder="`请输入${column.title}`" />
          </el-form-item>
        </template>
      </el-form>
      <div class="tip" style="color: #ff4949">提示： 辅助单位换算（基本单位）= 基本单位换算（辅助单位）</div>
      <div v-if="dialogForm.unit_name && dialogForm.unit_name2" class="tip" style="color: #ff4949">
        {{ dialogForm.unit_convert2 }}{{ dialogForm.unit_name }} =
        {{ dialogForm.unit_convert }}{{ dialogForm.unit_name2 }}
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="saving" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="saving" @click="onDialogConfirm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="`${selGoods.full_goods_name} 商品规格`" :visible.sync="goodsAttrDialogVisible" :show-close="false" :close-on-click-modal="false" custom-class="attr-dialog">
      <div class="dialog-box">
        <el-row style="padding: 10px 0;">
          <el-radio-group v-model="goodsAttrType">
            <el-radio :label="1">单规格</el-radio>
            <el-radio :label="2">多规格</el-radio>
          </el-radio-group>
        </el-row>
        <template v-if="goodsAttrType===1">
          <!-- <el-table :data="" border v-if="attrData.length">
            <template v-for="(item, index) in attrColumns">
              <el-table-column :prop="item.key" :label="item.title" :key="index">
                <template slot-scope="scope">
                  <div class="" v-if="item.key === ''">{{scope.row[item.key]}}</div>
                  <div class="" v-else>{{handleRowResult(item, scope.row)}}</div>
                </template>
              </el-table-column>
            </template>
            <el-table-column label="操作">
              <template slot-scope="{row, index}">
                <el-button type="primary" @click="handleTableOp({row, index,}, 'del')">删除</el-button>
              </template>
            </el-table-column>
          </el-table> -->
        </template>

        <template v-if="goodsAttrType===2">
          <el-row style="marginBottom: 20px">
            <el-select v-model="selAttr" :placeholder="`请选择商品规格模版`" style="marginRight:20px">
              <el-option v-for="item in goods_attr" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-button type="primary" :loading="saving" @click="handleAttrOp('add_attr_tem')">确认
            </el-button>
            <el-button type="default" :loading="saving" @click="handleAttrOp('goods_attr')">添加规格模板
            </el-button>
            <!-- <el-button type="primary" @click="generateAttr" :loading="saving">快速生成</el-button> -->
          </el-row>
          <div v-if="attrTem.length" class="attr-box">
            <div v-for="(item, index) in attrTem" :key="index" class="attr-wrap">
              <div class="attr-label">{{ item.attr.label }}
                <i class="el-icon-error icon" @click="handleAttrOp('del_attr', { 'temIndex': index })" />
              </div>
              <div v-if="item.attr_value.length" class="attr-value">
                <!-- <div v-for="(detail, index) in item.attr_value" :key="index">
                <div class="attr-value-item">{{detail.label}}</div>
              </div> -->
                <el-tag v-for="(tag, ti) in item.attr_value" :key="tag.name" class="attr-value-tag" closable @close="handleAttrOp('del_attr_item', { 'temIndex': index, 'vIndex': ti })">
                  {{ tag.label }}
                </el-tag>
                <el-input v-if="item.showInput" ref="saveTagInput" v-model="newAttrValue" class="add-attr-input" :placeholder="`请输入新的${item.attr.label}规格`" size="small" clearable @keyup.enter.native="handleAttrOp('add_attr_item', { 'temIndex': index })" @blur="handleAttrOp('add_attr_item', { 'temIndex': index })" />
                <el-button v-else class="button-new-tag" size="small" @click="handleAttrOp('showInput', { temIndex: index, show: true })">
                  添加新的{{ item.attr.label }}规格</el-button>
              </div>
              <div v-else>未获取 {{ item.attr.label }}-{{ item.attr.value }} 字典详情</div>
            </div>
          </div>
          <el-row v-if="attrTem.length" style="marginBottom: 10px">
            <el-button type="primary" icon="el-icon-plus" :loading="saving" @click="handleAttrOp('new_attr_tem')">添加新规格</el-button>
            <el-button type="success" :loading="saving" @click="generateAttr">快速生成</el-button>
          </el-row>

          <el-table v-if="attrData.length" :data="attrData" :border="true" height="250">
            <template v-for="(item, index) in attrColumns">
              <el-table-column :key="index" :prop="item.key" :label="item.label" sortable>
                <template slot-scope="scope">
                  <div v-if="item.key === ''" class="">{{ scope.row[item.key] }}</div>
                  <div v-else class="">{{ handleRowResult(item, scope.row) }}</div>
                </template>
              </el-table-column>
            </template>
            <el-table-column label="操作">
              <template slot-scope="{row, $index}">
                <el-button type="primary" @click="handleAttrOp('del_attr_data_item', {row, index: $index})">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="saving" @click="goodsAttrDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="saving" @click="onAttrConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { goodsIndex, goodsAdd, updateAttrConfig } from '../../api/goods';
import { createPayload, filterData } from '../../utils'
export default {
  name: 'Goods',
  data() {
    var handleUnitConvert = (rule, value, callback) => {
      console.log('this.dialogForm==', this.dialogForm);
      const dialogForm = this.dialogForm;
      if (!dialogForm.unit_name2.trim()) {
        callback();
      }
      else if (!dialogForm.unit_convert2) {
        console.log('dialogForm.unit_convert2==', dialogForm.unit_convert2);
        callback(new Error('请输入辅助单位换算'));
      }
      else if (dialogForm.unit_convert > dialogForm.unit_convert2) {
        callback(new Error('辅助单位 比 基本单位大'));
      }
      else {
        callback();
      }
    };
    return {
      columns: [
        // { title: '仓库', key: 'store_house_id', type: 'text', clearable: true, isFilter: true, isTable: false, isForm: false },
        { title: '商品名称', key: 'goods_name', type: 'text', clearable: true, isFilter: true, isTable: false, isForm: true },
        { title: '商品全称', key: 'full_goods_name', type: 'text', isFilter: false, isTable: true, isForm: true },
        // { title: '分类名称', key: 'cat_id', type: 'goodsCategoryDict', clearable: true, isFilter: false, isTable: true, isForm: true },
        { title: '排序', key: 'sort', type: 'number', sortable: true, isFilter: false, isTable: false, isForm: true },
        { title: '基本&辅助单位', key: 'unit_name', type: 'text', isFilter: false, isTable: false },
        { title: '单位换算', key: 'unit_convert', type: 'text', isFilter: false, isTable: true, width: 100 },
        { title: '基本单位', key: 'unit_name', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '辅助单位', key: 'unit_name2', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '基本单位换算', key: 'unit_convert', type: 'number', isFilter: false, isTable: false, isForm: true },
        { title: '辅助单位换算', key: 'unit_convert2', type: 'number', isFilter: false, isTable: false, isForm: true },
        { title: '库存', key: 'stock', type: 'text', isFilter: true, isTable: true }
      ],
      allList: [], // 接口返回数据（未处理）
      spreadList: [], // 商品规格展开数据
      list: [], // table 显示符合条件数据
      pageSizes: [50, 100, 150, 200],
      paging: { // 分页参数 page：当前页码，limit：每页条数，total： 总条数
        page: 1,
        limit: 20,
        total: 0
      },
      query: {},
      goodsSelects: [], // 存放商品名称，用于下拉选择。
      socketData: {}, // 统计库存信息

      dict: {},

      saving: false,
      dialogVisible: false,
      dialogColums: [],
      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: ['change', 'blur'] }
          // { required: true, message: '分类名称已存在', validator: cateNameValidator }
        ],
        full_goods_name: [
          { required: true, message: '请输入商品全称', trigger: ['change', 'blur'] }
          // { required: true, message: '分类名称已存在', validator: cateNameValidator }
        ],
        cat_id: [{ required: true, message: '请输入分类名称', trigger: ['change', 'blur'] }],
        unit_name: [{ required: true, message: '请输入基本单位', trigger: ['change', 'blur'] }],
        unit_name2: [{ required: false, message: '请输入辅助单位', trigger: ['change', 'blur'] }],
        unit_convert: [{ required: true, message: '请输入基本单位换算', trigger: ['change', 'blur'] }],
        unit_convert2: [
          { required: false, message: '请输入辅助单位换算', trigger: ['change', 'blur'] },
          { required: false, validator: handleUnitConvert }
        ]
      },
      dialogForm: {
        goods_name: '捷时达995硅酮结构密封胶',
        full_goods_name: '捷时达995',
        cat_id: 77,
        sort: 500,
        unit_name: '支',
        unit_name2: '件',
        unit_convert: 1,
        unit_convert2: 20
      },
      goods_attr: [],
      goodsAttrDialogVisible: false,
      selGoods: {},
      dictDetails: {},

      selAttr: '',
      attrTem: [],
      attrColumns: [
        { label: '', prop: '', price: '' }
      ],
      attrData: [],

      selTab: '1',
      goodsAttrType: 1,
      newAttrValue: ''

    };
  },
  computed: {
    goodsCategory() {
      return this.$store.getters.category?.data || [];
    },
    goodsCategoryDict() {
      return this.$store.getters.goodsCategoryDict;
    },
    system() {
      const system = this.$store.state.system;
      console.log('goods--system==', system);
      this.handleComputedUpdata(system);
      return system;
    },
    storeHouseList() {
      const curStore = this.$store.getters.curStore;
      const list = this.$store.state.store.storeHouseList.data;
      const curStoreHouseList = list.filter(d => d.store_id === curStore.id)
      return curStoreHouseList;
    },
    storeHouseDict() {
      return this.$store.getters.storeHouseDict;
    }
    // goods_attr() {
    //   const goods_attr = this.system?.dictDetails?.goods_attr?.data || [];
    //   return goods_attr;
    // },
  },
  watch: {
    // TODO 过滤
    query: {
      handler(val) {
        // const payload = utils.createPayload(val);
        // console.log('payload==', val, payload);
        // const payload = this.
      },
      deep: true
    }
  },
  created() {
    console.log('goods--this.$router==', this.$router);
    this.dict.goodsCategoryDict = this.$store.getters.goodsCategoryDict;
    console.log('goodsCategoryDict==', this.goodsCategoryDict);
    this.dialogColums = this.$json.cloneDeep(this.columns);
    this.getData();
  },
  methods: {
    // table row 样式
    handleRowClass({row, rowIndex}) {
      console.log('handleRowClass--row==', row, rowIndex);
      if (rowIndex === 0) {
        return 'goods_item_row';
      }
      else {
        const preRow = this.list[rowIndex - 1];
        if (preRow.id !== row.id) {
          return 'goods_item_row';
        }
        return '';
      }
    },
    // computed 数据变化 更新数据
    handleComputedUpdata(system) {
      this.dictDetails = system.dictDetails || {};
      this.goods_attr = system?.dictDetails?.goods_attr?.data || [];
    },
    // 获取商品数据
    async getData() {
      const { data } = await goodsIndex();
      this.allList = data?.list || [];
      // this.list = this.allList;
      // console.log('this.allList==', this.allList);
      this.handleSpreadList();
      // this.list = data?.list || [];
    },
    // 把商品数据中的规格展开；attrValue
    handleSpreadList() {
      const allList = this.$json.cloneDeep(this.allList);
      let spreadList = [];
      const socketData = {};
      const goodsSelects = [];  // 存储商品名称
      allList.forEach(d => {
        // 收集商品名称；
        goodsSelects.push({ label: d.goods_name, value: d.id });

        const attrValue = d.attrValue || [];

        if (attrValue.length > 0) {
          const goodsItem = attrValue.map(attr => {
            const attrItem = Object.assign(d, { attrConfigValue: attr, sku_id: attr.id });
            return this.$json.cloneDeep(attrItem);
          })
          spreadList = spreadList.concat(goodsItem);
        }
        else {
          spreadList.push({ ...d, attrConfigValue: null });
        }
      })
      console.log('spreadList==', spreadList);
      this.spreadList = spreadList;
      this.goodsSelects = goodsSelects;
      this.socketData = socketData;
      this.handleList();
    },
    // 把商品数据中的规格展开；attrConfig
    handleSpreadList2() {
      const allList = this.$json.cloneDeep(this.allList);
      let spreadList = [];
      const socketData = {};
      const goodsSelects = [];
      allList.forEach(d => {
        // 收集商品名称；
        goodsSelects.push({ label: d.goods_name, value: d.id });

        // 判断商品单规格 ｜ 多规格
        let attrConfig = [];
        if (d?.attrConfig?.config) {
          attrConfig = JSON.parse(d?.attrConfig?.config || '[]')
        }
        // 多规格
        if (attrConfig.length > 0) {
          const goodsItem = attrConfig.map(attr => {
            // socketData[`${d.id}_${attr.sku}`] = attr
            const attrItem = Object.assign(d, { attrConfigValue: attr });
            return this.$json.cloneDeep(attrItem);
          })
          spreadList = spreadList.concat(goodsItem);
        }
        else {
          spreadList.push({ ...d, attrConfigValue: null });
        }
      })
      console.log('spreadList==', spreadList);
      this.spreadList = spreadList;
      this.goodsSelects = goodsSelects;
      this.socketData = socketData;
      this.handleList();
    },
    // 展示符合条件的数据
    handleList() {
      this.list = filterData(this.spreadList, createPayload(this.query))
      this.paging.total = this.list.length;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    formatterColumn(row, column) {
      console.log('formatterColumn==', row, column);
      console.log('formatterColumn----------------');
      const property = column['property'];
      return `<el-tag>${row[property]}</el-tag>`;
    },
    // 处理table 单元格显示；
    handleRowResult(item, row) {
      console.log('handleRowResult--item', item, row, this.storeHouseDict);
      const value = row[item.key] || '';
      if (item.key === 'goods_name' || item.key === 'full_goods_name') {
        const sku = row?.attrConfigValue?.sku || '';
        return `<strong>${value}</strong> ${sku}`;
        // return '<strong>' + value + '</strong>' + sku;
      }
      if (item.key === 'stock') {
        const sku = row?.attrConfigValue?.sku;
        console.log('handleRowResult--stock--sku==', sku);
        if (sku && row?.attrValue && row?.attrValue.length > 0) {
          const skus = row?.attrValue.filter(d => d.sku === sku);
          console.log('handleRowResult--stock--skus==', skus);
          if (!skus || skus.length === 0) {
            return ''
          }
          return skus.map(d => {
            let skuValue = '';
            if (d.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
              const unitNum = d.stock % row.unit_convert2;
              const unitNum2 = Math.floor(d.stock / row.unit_convert2);
              if (unitNum2) {
                skuValue = `${unitNum2}${row.unit_name2}`;
              }
              if (unitNum) {
                skuValue = skuValue + `${unitNum}${row.unit_name}`;
              }
              // skuValue = `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
            }
            else {
              skuValue = `${d.stock}${row.unit_name}`
            }
            console.log('handleRowResult--skuValue==', skuValue);
            let storeName = d.store_house_id ? this.storeHouseDict[d.store_house_id].store_house_name : '';
            // if (storeName && storeName.indexOf('-')) {
            //   const indexOf = storeName.indexOf('-');
            //   indexOf < storeName.length-1 && (storeName = storeName.slice(indexOf+1))
            // }
            return (`${storeName}: ${skuValue}`)
            // return (`${this.storeHouseDict[d.store_house_id].store_house_name}: ${skuValue}`)
          }).join('\n')
        }

        // const socketKey = `${d.id}_${attr.store_house_id}_${attr.sku}`
        if (row.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
          const unitNum = row.stock % row.unit_convert2;
          const unitNum2 = Math.floor(row.stock / row.unit_convert2);
          return `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
        }
        return `${row.stock}${row.unit_name}`
      }
      if (item.key === 'cat_id') {
        const category = this.goodsCategoryDict[value]
        return category?.cat_name || value
      }
      if (item.key === 'unit_name') {
        return `${row.unit_name} / ${row.unit_name2 || '-'}`
      }
      if (item.key === 'unit_convert') {
        if (row.unit_name2) {
          return `${row.unit_convert2}${row.unit_name} / ${row.unit_convert}${row.unit_name2}`
        }
        return
      }
      return value;
    },
    // 条件筛选数据（废弃）
    handleFilter(type, value) {
      if (type === 'goods_name') {
        if (value) {
          this.list = this.allList.filter(d => {
            const index = d.goods_name.indexOf(value) || d.full_goods_name.indexOf(value)
            return index >= 0;
          })
        }
        else {
          this.list = this.$json.cloneDeep(this.allList)
        }
        // } else if (type === 'store_house_id') {
      }
      else if (type === 'cat_id') {
        this.list = value ? this.allList.filter(d => d.cat_id === value) : this.$json.cloneDeep(this.allList);
      }
      else if (type === 'stock') {
        // this.list = value ? this.allList.filter(d => d.cat_id === value) : this.$json.cloneDeep(this.allList);
      }
      else {
        this.list = this.$json.cloneDeep(this.allList)
      }
    },
    // table 操作事件；
    handleTableOp(type, row) {
      if (type === 'add') {
        this.$router.push({ path: `/goods/add/` })
        // this.dialogForm = {};
        // this.dialogVisible = true;
      }
      else if (type === 'edit') {
        this.dialogForm = this.$json.cloneDeep(row);
        this.dialogVisible = true;
      }
      else if (type === 'editAttr') {
        this.$router.push({ path: `/goods/edit/${row.id}` })
        // this.selGoods = this.$json.cloneDeep(row);
        // console.log('this.selGoods==', this.selGoods);
        // const attrConfig = this.selGoods.attrConfig;
        // this.attrTem = attrConfig?.attr || [];
        // this.attrData = attrConfig?.compose || [];
        // this.goodsAttrType = attrConfig?.attr?.length ? 2 : 1;

        // const attrColumns = [];
        // this.attrTem.forEach((d, i) => {
        //   attrColumns.push({ label: d.attr.label, key: d.attr.value, type: 'attr' })
        // })
        // this.attrColumns = attrColumns;
        // this.goodsAttrDialogVisible = true;
      }
      else if (type === 'addAttr') {
        this.selGoods.attr
          .this.goodsAttrDialogVisible = true;
      }
    },
    // dialog 提交；
    async onDialogConfirm() {
      let isValid = false;
      console.log('onDialogConfirm--this.$refs.dialogForm.==', this.$refs.dialogForm);
      this.$refs.dialogForm.validate(valid => {
        console.log('onDialogConfirm--valid==', valid);
        isValid = valid;
      })
      console.log('onDialogConfirm--this.saving ==', this.saving, isValid);
      if (this.saving) return this.$message.error('请勿重复提交');
      if (!isValid) return this.$message.error('请检查提交内容');

      this.saving = true;
      try {
        const payload = this.$json.cloneDeep(this.dialogForm);
        const { data } = await goodsAdd(payload);
        console.log('goodsAddCate==', data);
        if (data && data.length === 2) {
          if (data[1]) {
            this.getData();
            this.$message.success('添加成功')
            this.dialogVisible = false;
          }
          else {
            this.$message.error(`添加失败: ${payload.goods_name} ${payload.full_goods_name} 已存在`)
          }
        }
        else {
          this.$message.error(`异常：添加失败`)
        }
      }
      catch (e) {
        console.log('goodsAddCate--e==', e);
      }
      this.saving = false;
    },
    async onAttrConfirm() {
      console.log('this.selGoods==', this.selGoods);
      if (this.saving) return;
      let payload = {
        attr: [],
        value: []
      };
      if (this.goodsAttrType === 2) {
        if (this.attrData.length === 0) {
          this.$message.error(`请添加商品规格`)
          return;
        }
        payload = {
          attr: this.$json.cloneDeep(this.attrTem),
          compose: this.$json.cloneDeep(this.attrData)
        }
      }
      this.saving = true;
      try {
        const { data } = await updateAttrConfig({ config: JSON.stringify(payload), goods_id: this.selGoods.id });
        console.log('updateAttrConfig--data==', data);
        this.$message.success('操作成功')
        this.goodsAttrDialogVisible = false;
        this.saving = false;
        this.selGoods = {};
        this.attrTem = []
        this.attrData = [];
        this.goodsAttrType = 1;
        this.getData();
      }
      catch (e) {
        console.log('updateAttrConfig--e==', e);
        this.saving = false;
        this.$message.error(e)
      }
    },
    addAttr() {
      console.log('addAttr--this.selAttr==', this.selAttr, this.attrTem);
      // const attr = this.selAttr.attr;
      if (this.selAttr && this.attrTem.findIndex(d => d.attr.value === this.selAttr) < 0) {
        const attrTem = this.goods_attr.find(d => d.value === this.selAttr);
        this.attrTem.push({
          attr: attrTem,
          attr_value: this.$json.cloneDeep(this.dictDetails[this.selAttr])?.data || []
        })
        console.log('addAttr--attrTem==', this.attrTem);
      }
    },
    async handleAttrOp(type, data) {
      console.log('handleAttrOp==', type, data);
      if (type === 'add_attr_tem') {
        if (this.selAttr && this.attrTem.findIndex(d => d.attr.value === this.selAttr) < 0) {
          const attrTem = this.goods_attr.find(d => d.value === this.selAttr);
          this.attrTem.push({
            attr: attrTem,
            attr_value: this.$json.cloneDeep(this.dictDetails[this.selAttr])?.data || []
          })
          console.log('handleAttrOp--attrTem==', this.attrTem);
        }
      }
      else if (type === 'del_attr') {
        const { temIndex } = data;
        let isConfirm = false;
        try {
          isConfirm = await this.$confirm('确定要删除该规格吗？', '提示', { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' })
        }
        catch {
          isConfirm = false;
        }
        if (isConfirm) {
          this.attrTem.splice(temIndex, 1);
          this.$forceUpdate();
        }
        console.log('handleAttrOp--isConfirm==', isConfirm);
      }
      else if (type === 'del_attr_item') {
        const { temIndex, vIndex } = data;
        let isConfirm = false;
        try {
          isConfirm = await this.$confirm('确定要删除该规格吗？', '提示', { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' })
        }
        catch {
          isConfirm = false;
        }
        if (isConfirm) {
          this.attrTem[temIndex].attr_value.splice(vIndex, 1);
          this.$forceUpdate();
        }
      }
      else if (type === 'showInput') {
        const { temIndex } = data;
        this.attrTem[temIndex].showInput = true;
        this.$forceUpdate();
      }
      else if (type === 'add_attr_item') {
        const { temIndex } = data;
        if (this.newAttrValue) {
          console.log('this.attrTem[temIndex].attr_value.filter(d => d.label === this.newAttrValue).length==', this.attrTem[temIndex].attr_value.filter(d => d.label === this.newAttrValue).length);
          if (this.attrTem[temIndex].attr_value.findIndex(d => d.label === this.newAttrValue) < 0) {
            this.attrTem[temIndex].attr_value.push({
              name: this.newAttrValue,
              label: this.newAttrValue
            })
            this.newAttrValue = '';
          }
          else {
            this.$message.error(`${this.newAttrValue} 已存在`)
            return;
          }
        }
        this.attrTem[temIndex].showInput = false;
        console.log('this.attrTem==', this.attrTem);
        this.$forceUpdate();
      }
      else if (type === 'new_attr_tem') {
        // 添加新规格
        this.$message('开发中');
      }
      // else if (type === 'generate_attr') {
      // }
      else if (type === 'del_attr_data_item') {
        const { index } = data;
        let isConfirm = false;
        try {
          isConfirm = await this.$confirm('确定要删除该规格吗？', '提示', { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' })
        }
        catch {
          isConfirm = false;
        }
        if (isConfirm) {
          this.attrData.splice(index, 1);
          console.log('this.attrData==', this.attrData);
          this.$forceUpdate();
        }
      }
    },
    // 生成商品属性
    generateAttr() {
      // let oldAttr = this.selGoods.attr;
      const attrObj = [];
      const attrColumns = [];
      this.attrTem.forEach((d, i) => {
        attrObj[i] = d.attr_value.map(a => a.label);
        attrColumns.push({ title: d.attr.label, key: d.attr.value, type: 'attr' })
      })
      attrColumns.push({ title: '库存', key: 'socket' });
      const data = this.getSku(attrObj);
      console.log('getSku--data==', data);

      const attrData = data.map((d, i) => {
        // const sku = d.join(',');
        const obj = {};
        d.forEach((v, vi) => {
          console.log('generateAttr--v==', i, vi, v);
          obj[attrColumns[vi].key] = v;
        })
        return obj;
      })
      this.selGoods.attr = attrData;
      this.attrData = attrData;
      this.attrColumns = attrColumns || [];
      console.log('generateAttr--this.attrColumns==', this.attrColumns);
      console.log('generateAttr--this.attrData==', this.attrData);
    },
    getSku(data) {
      console.log('getSku--data==', data);
      const newArr = [];
      // let delimiter = '';
      const delimiter = '|(_##sku##_)|'; // 分隔符，避免sku中出现相同字符出现数据丢失情况
      function get(index, arr, str) {
        let list = '';
        for (let i = 0; i < arr[index].length; i++) {
          list = (str === '' ? '' : str + delimiter) + arr[index][i];
          console.log('get--list==', index, list);
          if (index + 1 === arr.length) {
            newArr.push(list.split(delimiter));
          }
          else {
            get(index + 1, arr, list);
          }
        }
        return newArr;
      }
      return get(0, data, '');
    },
    delAttr(index) {
      console.log('delAttr--index==', index);
    }
  }
}

</script>
<style lang="scss" scoped>
.container-box {
  padding: 20px;
}
.table-box {
  ::v-deep .el-table .cell {
    white-space: pre-line !important;
  }
  ::v-deep .goods_item_row {
    background-color: #fdf5e6;
  }
  .el-pagination {
    margin-top: 10px;
    text-align: right;
  }
}

::v-deep .el-dialog.attr-dialog {
  color: red;
  .goods-name {
    font-size: 20px;
    font-weight: bold;
  }
  .attr-box {
    .attr-wrap {
      margin-bottom: 20px;
      .attr-label {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 10px;
      }
      .attr-value {
        display: flex;
        flex-wrap: wrap;
        .attr-value-item {
          display: inline-block;
          margin: 0 10px 10px 0;
          padding: 5px;
          border: 1px solid #ccc;
          border-radius: 3px;
        }
        .attr-value-tag {
          margin-right: 10px;
        }
        .add-attr-input {
          width: 200px;
        }
      }
    }
  }
}
</style>
